<template>
  <div id="assessdetail">
    <el-form :model="editForm" label-width="200px" ref="editForm" :inline="true" style="padding:10px 0 0;clear:both" v-show="!pageLoading" :rules="editFormRules">
      <el-row>
        <el-col :span="12">
          <table cellspacing="0" cellpadding="0" class="mytable">
            <tr>
              <th style="width:120px">项目名称</th>
              <td>
                <template v-if="readOnly">{{editForm.title}}</template>
                <el-form-item prop="title" v-else>
                  <el-input v-model="editForm.title" style="width:300px"></el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>起止日期</th>
              <td>
                <template v-if="readOnly">{{editForm.beginDate}}至{{editForm.endDate}}</template>
                <el-form-item prop="projectDate" v-else>
                  <el-date-picker
                    v-model="editForm.projectDate"
                    type="daterange"
                    align="right"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :picker-options="pickerOptions"
                    value-format="yyyy-MM-dd">
                  </el-date-picker>
                </el-form-item>
              </td>
            </tr>
            <tr v-if="!editForm.id">
              <th>项目类型</th>
              <td>
                <el-radio-group v-model="editForm.type">
                  <el-radio :label="0">通用项目</el-radio>
                  <el-radio :label="1">定制项目</el-radio>
                </el-radio-group>
                <el-select v-if="editForm.type" v-model="editForm.type2" placeholder="请选择">
                  <el-option v-for="(item,index) in customList" :key="'custom'+index" :label="item" :value="index+1" />
                </el-select>
              </td>
            </tr>
            <tr v-else>
              <th>项目类型</th>
              <td>
                {{editForm.type?'定制项目：'+customList[editForm.type2-1]:'通用项目'}}
              </td>
            </tr>
            <tr v-if="!editForm.state&&!editForm.type">
              <th>上传配置文件</th>
              <td>
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  :action="this.$http.defaults.baseURL+this.$http.defaults.unitReportAPI +'api/file/upload/'"
                  :on-success="handleUploadSucc"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :on-error="uploadError"
                  :multiple="false"
                  :file-list="fileList"
                  :on-preview="handlePreview"
                  :before-upload="beforeUpload"
                >
                  <el-button type="primary">点击上传</el-button>
                </el-upload>
              </td>
            </tr>
            <tr>
              <th>备注</th>
              <td>
                <div v-if="readOnly" v-html="editForm.remark.replace(/\n/g,'<br>')"></div>
                <el-input v-else type="textarea" v-model="editForm.remark" style="width:100%"></el-input>
              </td>
            </tr>
          </table>
          <template v-if="!readOnly">
            <el-button type="primary" @click.native="editFormSubmit()" :loading="saveloading" style="margin-left:20px;">提交</el-button>
          </template>
        </el-col>
        <el-col :span="12">
          <h2 style="margin-top:0">填报单位</h2>
          <div style="clear:both;margin:10px 0;">
            <el-input
              v-model="filterText"
              placeholder="输入关键字进行过滤"
              style="width:220px;margin-right:10px;float:left"
            />
            <template  v-if="!editForm.state">
              <el-button v-if="selectAllBtn" type="primary" @click="selectTree(1)">全选</el-button>
              <el-button v-else type="primary" plain @click="selectTree(0)">取消</el-button>
            </template>
            <span style="line-height:40px">您已选择{{unitNum}}家单位</span>
          </div>
          <div style="clear:both;">
          <el-tree
            ref="tree"
            show-checkbox
            node-key="id"
            :expand-on-click-node="false"
            :data="treedata"
            :filter-node-method="filterNode"
            v-if="!editForm.state"
            @check-change="checkChange"
          />
          <el-tree
            default-expand-all
            ref="treeShow"
            node-key="id"
            :expand-on-click-node="false"
            :data="selectTreeData"
            :filter-node-method="filterNode"
            v-else
          />
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
export default {
  watch: {
    timestamp: {
      handler (val) {
        this.unitNum = 0
        // this.$refs['editForm'].resetFields()
        this.getUnits().then(() => {
          this.editFormReset()
          this.selectTree(0)
          if (this.projectId && this.projectId !== '') {
            this.getDetail(this.projectId)
          }
        })
      },
      immediate: true
    },
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  props: {
    timestamp: '',
    projectId: null,
    readOnly: false,
    showUnit: false
  },
  data () {
    return {
      fileList: [],
      unitNum: 0,
      customList: ['纪检机构编制人员统计'],
      selectTreeData: [],
      selectAllBtn: true,
      filterText: '',
      treedata: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      pageLoading: false,
      saveloading: false,
      editForm: {
        type: 0,
        type2: 2,
        projectDate: [],
        fileId: null,
        projectId: null,
        remark: '',
        title: '',
        unitIds: []
      },
      editFormRules: {
        title: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        projectDate: [
          { required: true, message: '必填项', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    getUnits () {
      return new Promise((resolve, reject) => {
        this.$http
          .get(this.$http.defaults.unitReportAPI + 'api/project/getUnitTree')
          .then(response => {
            if (response.data.success === true) {
              this.treedata = response.data.result
              resolve() // 数据加载成功，解析Promise
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
              reject(new Error('获取单位列表失败')) // 数据加载失败，拒绝Promise
            }
          })
          .catch(error => {
            console.log(error)
            reject(error) // 捕获错误，拒绝Promise
          })
      })
    },
    selectTree (flag) {
      if (this.$refs.tree) {
        if (flag) {
          this.selectAllBtn = false
          const keys = []
          for (let i = 0; i < this.treedata.length; i++) {
            keys.push(this.treedata[i].id)
          }
          console.log(keys)
          this.$refs.tree.setCheckedKeys(keys)
        } else {
          this.selectAllBtn = true
          this.$refs.tree.setCheckedKeys([])
          var nodes = this.$refs.tree.store.nodesMap
          for (var i in nodes) {
            nodes[i].expanded = false
          }
        }
      }
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    editFormSubmit (reEnterFlag) {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (!this.editForm.projectId && !this.editForm.type && (!this.files || this.files.length === 0)) {
            this.$message({
              message: '新增项目时必须上传配置文件',
              type: 'error'
            })
            return false
          }
          let unitIds = null
          if (!this.editForm.state) {
            unitIds = this.$refs.tree.getCheckedKeys().filter(item => item < 1000)
            if (!unitIds || unitIds.length === 0) {
              this.$message({
                message: '至少选择一家填报单位',
                type: 'error'
              })
              return false
            }
          }
          this.saveloading = true
          let beginDate = null
          let endDate = null
          if (this.editForm.projectDate && this.editForm.projectDate !== []) {
            beginDate = this.editForm.projectDate[0]
            endDate = this.editForm.projectDate[1]
          }
          let para = {
            projectId: this.editForm.projectId,
            customType: this.editForm.type ? this.editForm.type2 : 0,
            beginDate: beginDate,
            endDate: endDate,
            title: this.editForm.title,
            remark: this.editForm.remark,
            unitIds: unitIds,
            fileId: this.files && this.files.length > 0 ? this.files[0].id : null
          }
          let url = 'api/project/saveProject'
          this.$http
            .post(this.$http.defaults.unitReportAPI + url, para)
            .then(response => {
              this.saveloading = false
              if (response.data.success) {
                this.editFormReset()
                this.$emit('dialogHide', true)
                this.$message({
                  message: '提交成功！',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '保存失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              this.saveloading = false
              console.log(error)
              this.$message({
                message: '网络保存失败:' + error,
                type: 'error'
              })
            })
        }
      })
    },
    editFormReset () {
      this.editForm = {
        type: 0,
        type2: 1,
        projectDate: [],
        fileId: null,
        projectId: null,
        remark: '',
        title: '',
        unitIds: []
      }
      if (this.$refs['editForm']) {
        this.$refs['editForm'].resetFields()
      }
      this.files = []
      this.fileList = []
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
    },
    beforeUpload (file) {
      console.log('文件类型')
      console.log(file.name)
      const isFormat = file.name.indexOf('.dwtb') > 0
      // const isLt5M = file.size / 1024 / 1024 < 500
      if (!isFormat) {
        this.$message.error('配置文件只能是 .dwtb 格式!')
      } else {
        this.saveloading = true
      }
      return isFormat
    },
    formatFiles (files) {
      if (files && files.length > 0) {
        const newfiles = []
        for (let i = 0; i < files.length; i++) {
          newfiles.push({ name: files[i].fileName + '.' + files[i].fileType, id: files[i].id })
        }
        console.log(newfiles)
        return newfiles
      }
    },
    formatSuccList (fileList) {
      if (fileList && fileList.length > 0) {
        const newfiles = []
        let i = fileList.length - 1
        if (fileList[i].response) {
          newfiles.push({ name: fileList[i].response.result[0].fileName + '.' + fileList[i].response.result[0].fileType, id: fileList[i].response.result[0].id })
        } else {
          newfiles.push(fileList[i])
        }
        console.log(newfiles)
        return newfiles
      }
    },
    handleUploadSucc (response, file, fileList) {
      console.log(response)
      this.saveloading = false
      if (response.success) {
        console.log(response.result[0])
        this.files = []
        this.files.push(response.result[0])

        this.fileList = this.formatSuccList(fileList)
        this.$message({
          message: '上传成功！' + response.message,
          type: 'success'
        })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error'
        })
      }
    },
    beforeRemove (file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定删除 ${file.name}？`)
      }
    },
    handleRemove (file, fileList) {
      if (file && file.status === 'success') {
        console.log(file, fileList)
        const fid = file.id
        const url = 'api/file/remove'
        let para = {
          params: {
            id: fid
          }
        }
        this.$http.get(this.$http.defaults.unitReportAPI + url, para).then(res => {
          console.log('删除成功:', res)
          if (res.data.success === true) {
            const newfiles = []
            for (let i = 0; i < this.files.length; i++) {
              if (this.files[i].id !== fid) {
                newfiles.push(this.files[i])
              }
            }
            this.files = newfiles
            this.fileList = this.formatFiles(this.files)
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
          }
        })
      }
    },
    uploadError (err) {
      this.saveloading = false
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error'
      })
    },
    handlePreview (file) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(this.$http.defaults.baseURL + this.$http.defaults.unitReportAPI + 'api/file/download?id=' + file.id, file.name)
      } else {
        var link = document.createElement('a')
        link.download = file.name
        link.href = this.$http.defaults.baseURL + this.$http.defaults.unitReportAPI + 'api/file/download?id=' + file.id
        link.click()
        console.log(this.$http.defaults.unitReportAPI + 'api/file/download?id=' + file.id)
        window.URL.revokeObjectURL(link.href)
      }
    },
    getDetail (id) {
      this.unitNum = 0
      this.pageLoading = true
      this.$http
        .get(this.$http.defaults.unitReportAPI + `api/project/getProjectById?id=` + id)
        .then(response => {
          let obj = response.data.result
          obj.type = obj.customType
          obj.type2 = 1
          obj.projectDate = [obj.beginDate, obj.endDate]
          this.editForm = obj
          if (this.editForm.state !== 0) {
            this.selectTreeData = []
            this.treedata.forEach(item => {
              let showChildren = []
              item.children.forEach(it => {
                if (response.data.result.unitIds.indexOf(it.id) > -1) {
                  showChildren.push(it)
                }
              })
              if (showChildren.length > 0) {
                item.children = showChildren
                this.selectTreeData.push(item)
              }
            })
            this.unitNum = response.data.result.unitIds.length
          } else {
            this.$refs.tree.setCheckedKeys(response.data.result.unitIds)
            this.$nextTick(() => {
              this.unitNum = this.$refs.tree.getCheckedKeys().filter(item => item < 1000).length
            })
          }
          this.editForm.projectId = this.editForm.id
          this.pageLoading = false
        })
        .catch(error => {
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    checkChange () {
      this.unitNum = this.$refs.tree.getCheckedKeys().filter(item => item < 1000).length
    }
  }
}
</script>
<style>
#assessdetail .el-upload-list__item{
  width: 250px;
}
#assessdetail a{
  width: 200px;
}
.assessdetail .el-tabs__header{
  height: 29px;
  background: #FAFAFA;
  line-height: 30px;
  font-family: '宋体';
  padding:0 20px;
  border-bottom: 2px solid #E4E7ED;
  margin:0;
}
.assessdetail .el-tabs__item{
  line-height: 30px;
  height: 30px;
  font-weight:bolder;
}
  .cardtab .el-tabs__header{
    padding:0 !important;
    border-bottom:1px solid #E4E7ED;
  }
  #assessdetail .wboxs{
    height:45px;
    padding-top:0;
    margin-bottom: 10px;
  }
  .wboxs{
    padding:5px 15px;
    width: calc(100% - 30px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
</style>

<style scoped>
  .tickettable th{
    font-weight:lighter;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
    text-align: center;
  }
  .tickettable{
    width: 100%;
    border-left: 1px solid #95B8E7;
    border-top: 1px solid #95B8E7;
  }
  .tickettable td, .tickettable th{
    padding:5px 10px;
    margin:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体';
    border-bottom: 1px solid #95B8E7;
    border-right: 1px solid #95B8E7;
  }
  .tickettable td{
    vertical-align: middle;
    text-align: center;
    font-weight: bolder;
  }
  .mytable{
    border-top: 1px solid #74a6cc;
    border-left: 1px solid #74a6cc;
    margin:0 10px 10px;
    width: calc(100% - 20px);
  }
  .mytable th{
    padding: 10px;
    border-right: 1px solid #74a6cc;
    border-bottom: 1px solid #74a6cc;
    vertical-align: top;
    line-height: 150%;
    background: #FAFAFA;
    width:200px;
    text-align:right;
  }
  .mytable td{
    padding: 10px;
    border-right: 1px solid #74a6cc;
    border-bottom: 1px solid #74a6cc;
    vertical-align: top;
    line-height: 150%;
  }
</style>
